package com.zero.rpc.easy.proxy;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.zero.rpc.easy.model.RpcRequest;
import com.zero.rpc.easy.model.RpcResponse;
import com.zero.rpc.easy.serializer.JdkSerializer;
import com.zero.rpc.easy.serializer.Serializer;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 *
 * 一个代理 用来对 封装请求，进行代理
 * */
public class ServiceProxy implements InvocationHandler {

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {


//        System.out.println("proxy"+ proxy +" method:" + method + " args:" + args);

        //  指定序列化器
        Serializer serializer = new JdkSerializer();
        // 构建请求
        RpcRequest args1 = RpcRequest.builder()
                .serviceName(method.getDeclaringClass().getName())
                .methodName(method.getName())
                .parameterTypes(method.getParameterTypes())
                .args(args).build();

        // 请求序列化
        byte[] bodyBytes = serializer.serialize(args1);

        // 发送请求
        try(HttpResponse httpResponse = HttpRequest.post("http://localhost:8080")
                .body(bodyBytes)
                .execute()){
            byte[] results = httpResponse.bodyBytes();
            // 反序列化
            RpcResponse rpcResponse = serializer.deserialize(results, RpcResponse.class);
            return rpcResponse.getData();
        }catch (Exception e){
           e.printStackTrace();
        }

        return null;
    }
}
